package cn.hsw.component.web.validated.valid;

import cn.hsw.component.core.util.Validator;
import cn.hsw.component.web.validated.annotations.MustOnly;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;

/**
 * 唯一验证
 * @author 李子木
 */
public class MustOnlyValid implements ConstraintValidator<MustOnly, Object> {

    @Autowired
    ApplicationContext context;

    MustOnly annotation;


    @Override
    public void initialize(MustOnly constraintAnnotation) {
        annotation = constraintAnnotation;
    }

    @SneakyThrows
    @Override
    public boolean isValid(Object s, ConstraintValidatorContext constraintValidatorContext) {

        if(Validator.isEmpty(s)){
            return false;
        }

        Method method = annotation.beanClass().getMethod(annotation.method(), s.getClass());

        Object bean = context.getBean(annotation.beanClass());

        Object invoke = method.invoke(bean, s);

        return Validator.isNull(invoke);
    }
}
